package cn.ug.member.web.controller;


import cn.ug.activity.bean.ChannelActivationBean;
import cn.ug.activity.bean.ChannelBean;
import cn.ug.bean.base.*;
import cn.ug.bean.type.ResultType;
import cn.ug.config.Config;
import cn.ug.core.SerializeObjectError;
import cn.ug.enums.ChannelEnum;
import cn.ug.feign.ChannelService;
import cn.ug.feign.CouponDonationService;
import cn.ug.member.bean.InvitationBean;
import cn.ug.member.bean.MemberDetailBean;
import cn.ug.member.bean.MemberInfoBean;
import cn.ug.member.bean.request.*;
import cn.ug.member.bean.response.*;
import cn.ug.member.bean.status.CommonConstants;
import cn.ug.member.service.MemberUserService;
import cn.ug.pay.bean.TradeTotalAmountBean;
import cn.ug.util.*;
import cn.ug.web.controller.ExportExcelController;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

import static org.springframework.web.bind.annotation.RequestMethod.*;

/**
 * 会员服务
 *
 * @author ywl
 * @date 2018/1/12
 */
@RestController
@RequestMapping("memberUser")
public class MemberUserController {
    @Resource
    private MemberUserService memberUserService;
    @Resource
    private Config config;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private CouponDonationService couponDonationService;
    private static Logger logger = LoggerFactory.getLogger(MemberUserController.class);

    @PostMapping("/password/wrong/times")
    public SerializeObject modifyWrongTimes(String memberId, int type, int wrongTimes, int status) {
        if (type == 1) {
            if (memberUserService.modifyPasswordWrongTimes(memberId, wrongTimes, status)) {
                return new SerializeObject(ResultType.NORMAL, "00000001");
            }
        } else if (type == 2) {
            if (memberUserService.modifyTradePasswordWrongTimes(memberId, wrongTimes, status)) {
                return new SerializeObject(ResultType.NORMAL, "00000001");
            }
        }
        return new SerializeObject(ResultType.ERROR, "00000005");
    }

    /**
     * 查询列表
     *
     * @param accessToken         登录成功后分配的Key
     * @param memberUserParamBean 会员请求参数
     * @return 分页数据
     */
    @RequestMapping(value = "list", method = GET)
    public SerializeObject<DataTable<MemberUserBaseBean>> query(@RequestHeader String accessToken, MemberUserParamBean memberUserParamBean) {
        if (memberUserParamBean.getPageSize() <= 0) {
            memberUserParamBean.setPageSize(config.getPageSize());
        }
        DataTable<MemberUserBaseBean> dataTable = memberUserService.query(memberUserParamBean);
        return new SerializeObject<>(ResultType.NORMAL, dataTable);
    }


    @GetMapping("/detail")
    public SerializeObject<MemberDetailBean> query(@RequestHeader String accessToken, String memberId) {
        return new SerializeObject<>(ResultType.NORMAL, memberUserService.getMemberDetail(memberId));
    }

    /**
     * 根据ID查找信息
     *
     * @param accessToken 登录成功后分配的Key
     * @param id          ID
     * @return 记录集
     */
    @RequestMapping(value = "{id}", method = GET)
    public SerializeObject find(@RequestHeader String accessToken, @PathVariable String id) {
        if (StringUtils.isBlank(id)) {
            return new SerializeObject(ResultType.NORMAL, "00000002");
        }
        MemberUserFindBean entity = memberUserService.queryMemberUserById(id);
        if (null == entity || StringUtils.isBlank(entity.getId())) {
            return new SerializeObject(ResultType.NORMAL, "00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    /**
     * 新增信息（id为null、''）或修改信息（id不为空）
     *
     * @param accessToken 登录成功后分配的Key
     * @param entity      记录集
     * @return 是否操作成功
     */
    @RequestMapping(method = POST)
    public SerializeObject update(@RequestHeader String accessToken, MemberUserFindBean entity) {
        if (StringUtils.isBlank(entity.getId())) {
            memberUserService.save(entity);
        } else {
            memberUserService.update(entity);
        }
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 冻结用户
     *
     * @param accessToken 登录成功后分配的Key
     * @param id          ID数组
     * @return 是否操作成功
     */
    @RequestMapping(value = "disable", method = PUT)
    public SerializeObject disable(@RequestHeader String accessToken, String[] id) {
        memberUserService.updateStatus(id, CommonConstants.LOCK);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 解冻用户
     *
     * @param accessToken 登录成功后分配的Key
     * @param id          ID数组
     * @return 是否操作成功
     */
    @RequestMapping(value = "enable", method = PUT)
    public SerializeObject enable(@RequestHeader String accessToken, String[] id) {
        memberUserService.updateStatus(id, CommonConstants.UNLOCK);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 查找用户
     *
     * @param id 用户id
     * @return 用户信息
     */
    @RequestMapping(value = "findById", method = GET)
    public SerializeObject<MemberUserBean> findById(String id) {
        MemberUserBean entity = memberUserService.findById(id);
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    @RequestMapping(value = "/total/users", method = GET)
    public SerializeObject<Integer> countTotalUsers() {
        int num = memberUserService.countTotalUsers();
        return new SerializeObject<>(ResultType.NORMAL, num);
    }

    @GetMapping(value = "/list/userId")
    public SerializeObject<DataTable<MemberInfoBean>> listUserId(Integer page, Integer size) {
        int total = memberUserService.countTotalUsers();
        if (total > 0) {
            List<MemberInfoBean> list = memberUserService.listUsersId(PaginationUtil.getOffset(page, size), PaginationUtil.getPageSize(size));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberInfoBean>(page, size, total, list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberInfoBean>(page, size, total, new ArrayList<MemberInfoBean>()));
    }

    @GetMapping(value = "/list/userId/with/mobiles")
    public SerializeObject<List<MemberInfoBean>> listUserId(String donationId) {
        if (StringUtils.isNotBlank(donationId)) {
            SerializeObject<String> bean = couponDonationService.getMobiles(donationId);
            if (bean != null && bean.getCode() == ResultType.NORMAL) {
                String[] infos = StringUtils.split(bean.getData(), ConstantUtil.COMMA);
                List<String> partners = new ArrayList<String>();
                for (String mobile : infos) {
                    partners.add(mobile);
                }
                List<MemberInfoBean> list = memberUserService.listUsersId(partners);
                return new SerializeObject<>(ResultType.NORMAL, list);
            }
        }
        return new SerializeObject<>(ResultType.NORMAL, new ArrayList<MemberInfoBean>());
    }

    /**
     * 查找用户
     *
     * @param loginName 用户名
     * @return 用户信息
     */
    @RequestMapping(value = "findByLoginName", method = GET)
    public SerializeObject<MemberUserBean> findByLoginName(String loginName) {
        MemberUserBean entity = memberUserService.findByLoginName(loginName);
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    /**
     * 忘记密码
     *
     * @param id       用户ID
     * @param password 密码
     * @return 用户信息
     */
    @RequestMapping(value = "forgetPassword", method = PUT)
    public SerializeObject forgetPassword(String id, String password) {
        memberUserService.forgetPassword(id, password);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 修改密码
     *
     * @param password    密码
     * @param newPassword 新密码
     * @return 用户信息
     */
    @RequestMapping(value = "updatePassword", method = PUT)
    public SerializeObject updatePassword(@RequestHeader String accessToken, String password, String newPassword) {
        memberUserService.updatePassword(password, newPassword);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 注册用户
     *
     * @param mobile 手机号码
     * @return 密码
     */
    @RequestMapping(value = "register", method = POST)
    public SerializeObject register(int source, String mobile, String password,
                                    @RequestParam(value = "inviteCode", required = false) String inviteCode,
                                    @RequestParam(value = "channelId", required = false) String channelId,
                                    @RequestParam(value = "staffId", required = false) String staffId,
                                    @RequestParam(value = "lotteryId", required = false) Integer lotteryId) {
        if (!ValidatorUtil.isMobile(mobile)) {
            return new SerializeObjectError("14000215");
        }
        if (!ValidatorUtil.isLoginPassword(password)) {
            return new SerializeObjectError("14000222");
        }

        String friendId = "";
        ChannelBean bean = new ChannelBean();
        int amount = 0;
        if (StringUtils.isEmpty(staffId) || "0".equals(staffId)) {
            if (StringUtils.isNoneBlank(inviteCode)) {
                MemberUserBean userBean = memberUserService.findByInviteCode(inviteCode);
                if (userBean != null && StringUtils.isNotBlank(userBean.getId())) {
                    friendId = userBean.getId();
                    if (StringUtils.isNotBlank(userBean.getStaffId()) && !StringUtils.equals(userBean.getStaffId(), String.valueOf(0))) {
                        staffId = userBean.getId();
                    }
                }
            }

            MemberUserBean user = memberUserService.findByMobile(mobile);
            if (user != null && StringUtils.isNoneBlank(user.getId())) {
                return new SerializeObjectError("14000202");
            }

            if (StringUtils.isNotBlank(channelId)) {
                SerializeObject<ChannelBean> channelBean = channelService.get(channelId);
                if (channelBean != null && channelBean.getCode() == ResultType.NORMAL) {
                    bean = channelBean.getData();
                    amount = bean.getAmount();
                }
            }
        }

        if (StringUtils.isNotEmpty(staffId)) {
            friendId = "";
            bean = null;
        }

        if (memberUserService.register(mobile, password, friendId, bean, source, staffId, lotteryId, amount)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObjectError("14000224");
        }
    }

    @RequestMapping(value = "/shortcut/register", method = POST)
    public SerializeObject shortcutRegister(int source, String mobile,
                                            @RequestParam(value = "inviteCode", required = false) String inviteCode,
                                            @RequestParam(value = "channelId", required = false) String channelId,
                                            @RequestParam(value = "staffId", required = false) String staffId,
                                            @RequestParam(value = "lotteryId", required = false) Integer lotteryId) {
        logger.info("channelId=[" + channelId + "]");
        if (!ValidatorUtil.isMobile(mobile)) {
            return new SerializeObjectError("14000215");
        }
        String friendId = "";
        ChannelBean bean = new ChannelBean();
        int amount = 0;
        if (StringUtils.isEmpty(staffId) || "0".equals(staffId)) {
            if (StringUtils.isNoneBlank(inviteCode)) {
                MemberUserBean userBean = memberUserService.findByInviteCode(inviteCode);
                if (userBean != null && StringUtils.isNotBlank(userBean.getId())) {
                    friendId = userBean.getId();
                    channelId = ChannelEnum.INVITATION.getId();
                    if (StringUtils.isNotBlank(userBean.getStaffId()) && !StringUtils.equals(userBean.getStaffId(), String.valueOf(0))) {
                        staffId = userBean.getId();
                    }
                }
            }

            if (StringUtils.isNotBlank(channelId)) {
                SerializeObject<ChannelBean> channelBean = channelService.get(channelId);
                if (channelBean != null && channelBean.getCode() == ResultType.NORMAL) {
                    bean = channelBean.getData();
                    amount = bean.getAmount();
                }
            }
        }

        if (memberUserService.register(mobile, friendId, bean, source, staffId, lotteryId, amount)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObjectError("14000224");
        }
    }

    @RequestMapping(value = "/activation")
    public SerializeObject activation(String uuid) {
        logger.info("今日头图App下载激活：uuid " + uuid + "]");
        if (StringUtils.isNotBlank(uuid) && uuid.length()<30){
            try {
                uuid = getMD5(uuid);
            } catch (NoSuchAlgorithmException e) {
                logger.info("md5操作失败");
                e.printStackTrace();
            }
        }
        SerializeObject<ChannelActivationBean> activationBean = channelService.getActivation(uuid);
        String result = null;
        if (activationBean != null && activationBean.getData() != null && StringUtils.isNotBlank(activationBean.getData().getCallbackUrl())) {
            logger.info("转化成功接口回传 :" + activationBean.getData().getCallbackUrl() + "]");
            result = invoke(activationBean.getData().getCallbackUrl());
            if (StringUtils.isNotBlank(result)) {
                JSONObject data = JSONObject.parseObject(result);
                if (data != null && data.containsKey("ret") && data.getIntValue("ret") == 0) {
                    channelService.transform(uuid);
                }
            }
        }
        return new SerializeObject(ResultType.NORMAL, "00000001", result);
    }

    /**
     * 获取用户邀请好友详情
     *
     * @param accessToken
     * @param page
     * @param memberId    用户id
     * @return
     */
    @GetMapping(value = "/invitation/list")
    public SerializeObject<DataTable<InvitationBean>> listInvitation(@RequestHeader String accessToken, Page page, String memberId) {
        memberId = UF.toString(memberId);
        int type = 1;
        int total = memberUserService.countRecords(memberId, type);
        page.setTotal(total);
        if (total > 0) {
            List<InvitationBean> list = memberUserService.listRecords(memberId, type, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<InvitationBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<InvitationBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<InvitationBean>()));
    }

    /**
     * 成功邀请人数
     *
     * @param memberId
     * @return
     */
    @GetMapping(value = "/invitation/sum")
    public SerializeObject<Integer> sumInvitation(String memberId) {
        memberId = UF.toString(memberId);
        return new SerializeObject<>(ResultType.NORMAL, memberUserService.sumInvitation(memberId));
    }

    /**
     * 设置交易密码
     *
     * @param payPassword 交易密码
     * @return
     */
    @RequestMapping(value = "setPayPassword", method = POST)
    public SerializeObject setPayPassword(@RequestHeader String accessToken, String payPassword) {
        memberUserService.setPayPassword(payPassword);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 修改交易密码
     *
     * @param payPassword    当前交易密码
     * @param newPayPassword 新交易密码
     * @return
     */
    @RequestMapping(value = "updatePayPassword", method = POST)
    public SerializeObject updatePayPassword(@RequestHeader String accessToken, String payPassword, String newPayPassword) {
        memberUserService.updatePayPassword(payPassword, newPayPassword);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 更新会员实名信息
     *
     * @param memberUserBaseParmBean 会员实名信息
     * @return
     */
    @RequestMapping(value = "updateBaseInfo", method = POST)
    public SerializeObject updateBaseInfo(@RequestBody MemberUserBaseParmBean memberUserBaseParmBean) {
        memberUserService.updateBaseInfo(memberUserBaseParmBean);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 验证交易密码是否正确
     *
     * @param memberId    会员id
     * @param payPassword 交易密码
     * @return
     */
    @RequestMapping(value = "validatePayPassword", method = POST)
    public SerializeObject validatePayPassword(String memberId, String payPassword) {
        boolean flag = memberUserService.validatePayPassword(memberId, payPassword);
        if (flag) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "14000209");
        }
    }

    /**
     * 验证身份是否正确
     *
     * @param muIdentityParamBean
     * @return
     */
    @RequestMapping(value = "validateMemberIdentity", method = POST)
    public SerializeObject validateMemberIdentity(MemberUserIdentityParamBean muIdentityParamBean) {
        memberUserService.validateMemberIdentity(muIdentityParamBean);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 更新登录来源
     *
     * @param memberId    会员id
     * @param loginSource 登录来源 2：android 3:ios
     * @return
     */
    @RequestMapping(value = "updateLoginSource", method = GET)
    public SerializeObject updateLoginSource(String memberId, Integer loginSource) {
        memberUserService.updateLoginSource(memberId, loginSource);
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    /**
     * 用户购金列表
     * @param accessToken
     * @param memberUserBuyGoldParamBean
     * @return
     */
    @RequestMapping(value = "buyGold/list", method = GET)
    public SerializeObject<DataTable<MemberUserBuyGoldBean>> buyGoldlist(@RequestHeader String accessToken, MemberUserBuyGoldParamBean memberUserBuyGoldParamBean) {
        if (memberUserBuyGoldParamBean.getPageSize() <= 0) {
            memberUserBuyGoldParamBean.setPageSize(config.getPageSize());
        }
        DataTable<MemberUserBuyGoldBean> dataTable = memberUserService.queryBuyGoldList(memberUserBuyGoldParamBean);
        return new SerializeObject<>(ResultType.NORMAL, dataTable);
    }

    /**
     * 用户行为列表
     * @param accessToken
     * @param memberUserBuyGoldParamBean
     * @return
     */
    @RequestMapping(value = "behavior/list", method = GET)
    public SerializeObject<DataTable<MemberUserBehaviorBean>> behaviorlist(@RequestHeader String accessToken, MemberUserBehaviorParamBean memberUserBuyGoldParamBean) {
        if (memberUserBuyGoldParamBean.getPageSize() <= 0) {
            memberUserBuyGoldParamBean.setPageSize(config.getPageSize());
        }
        //解决一个奇怪的问题 前端传值会在前面加一个逗号。。
        if (StringUtils.isNotBlank(memberUserBuyGoldParamBean.getOrder()) && memberUserBuyGoldParamBean.getOrder().contains(",")){
            memberUserBuyGoldParamBean.setOrder(memberUserBuyGoldParamBean.getOrder().replaceAll(",",""));
            memberUserBuyGoldParamBean.setSort(memberUserBuyGoldParamBean.getSort().replaceAll(",",""));
        }
        DataTable<MemberUserBehaviorBean> dataTable = memberUserService.behaviorlist(memberUserBuyGoldParamBean);
        return new SerializeObject<>(ResultType.NORMAL, dataTable);
    }

    /**
     * 用户列表导出
     * @return
     */
    @RequestMapping(value = "/export", method = GET)
    public void export(HttpServletResponse response, MemberUserParamBean memberUserParamBean) {
        String[] columnNames = {"序号", "手机号", "姓名", "身份证号", "注册时间", "状态", "绑卡时间", "渠道", "持有提单总克数（克）", "回租提单克数（克）", "账户余额（元）", "金豆余额（粒）", "最近回租时间", "回租到期时长（天）", "邀请人姓名", "邀请人手机号"};
        String[] columns = {"index", "mobile", "name", "idCard", "addTimeString", "userStatus", "tiedCardTime", "channelName", "tbTotalGram", "tblTotalGram", "usableAmount", "usableBean", "newLeasebackDate", "leasebackDays", "invitationName", "invitationMobile"};
        String fileName = "用户信息列表";
        memberUserParamBean.setPageSize(Integer.MAX_VALUE);
        DataTable<MemberUserBaseBean> dataTable = memberUserService.query(memberUserParamBean);

        ExportExcelController<MemberUserExportBaseBean> export = new ExportExcelController<>();
        export.exportExcel(fileName, fileName, columnNames, columns,
                wrapPutGoldBeanData(dataTable.getDataList()), response, ExportExcelUtil.EXCEL_FILE_2003);
    }

    /**
     * 用户购金列表导出
     * @return
     */
    @RequestMapping(value = "/buyGold/export", method = GET)
    public void buyGoldExport(HttpServletResponse response, MemberUserBuyGoldParamBean memberUserBuyGoldParamBean) {
        String[] columnNames = {"序号", "手机号", "姓名", "最高购买克重总数（克）", "购金平均规格", "最近回租结束时间", "最近回租到期时长（天）", "上次回租结束时间", "上次回租到期时长（天）", "回租中克重（克）", "累计复投次数（次）", "累计复投克重（克）", "回租总收益（元)", "黄金买卖收益（元)"};
        String[] columns = {"index", "mobile", "name", "maxBuyGram", "averageBuyGram", "newLeasebackEndDate", "newLeasebackDays", "frontLeasebackEndDate", "frontLeasebackDays", "leasebackGram", "totalRepeatNum", "totalRepeatGram", "totalIncomeAmount", "buySellIncomeAmount"};
        String fileName = "用户购金情况";
        memberUserBuyGoldParamBean.setPageSize(Integer.MAX_VALUE);
        DataTable<MemberUserBuyGoldBean> dataTable = memberUserService.queryBuyGoldList(memberUserBuyGoldParamBean);
        int index = 1;
        List<MemberUserBuyGoldBean> memberUserBuyGoldBeanList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(dataTable.getDataList())) {
            for (MemberUserBuyGoldBean memberUserBuyGoldBean : dataTable.getDataList()) {
                memberUserBuyGoldBean.setIndex(index++);
                memberUserBuyGoldBeanList.add(memberUserBuyGoldBean);
            }
        }
        ExportExcelController<MemberUserBuyGoldBean> export = new ExportExcelController<>();
        export.exportExcel(fileName, fileName, columnNames, columns,
                memberUserBuyGoldBeanList, response, ExportExcelUtil.EXCEL_FILE_2003);
    }

    /**
     * 用户行为列表导出
     *
     * @param response
     * @param memberUserBehaviorParamBean
     */
    @RequestMapping(value = "/behavior/export", method = GET)
    public void behaviorExport(HttpServletResponse response, MemberUserBehaviorParamBean memberUserBehaviorParamBean) {
        String[] columnNames = {"序号", "手机号", "姓名", "平均回租周期（天）", "最高回租周期（天）", "优惠券使用次数（次）", "优惠券总金额（mg）", "邀请人数（人）", "邀请购金总克重（克）", "渠道来源"};
        String[] columns = {"index", "mobile", "name", "averageLeasebackDay", "maxLeasebackDay", "couponNum", "couponGram", "invitationNum", "invitationBuyGram", "channelName"};
        String fileName = "用户购金情况";
        memberUserBehaviorParamBean.setPageSize(Integer.MAX_VALUE);
        DataTable<MemberUserBehaviorBean> dataTable = memberUserService.behaviorlist(memberUserBehaviorParamBean);
        int index = 1;
        List<MemberUserBehaviorBean> memberUserBehaviorParamBeans = new ArrayList<>();
        if (!CollectionUtils.isEmpty(dataTable.getDataList())) {
            for (MemberUserBehaviorBean memberUserBehaviorBean : dataTable.getDataList()) {
                memberUserBehaviorBean.setIndex(index++);
                memberUserBehaviorParamBeans.add(memberUserBehaviorBean);
            }
        }
        ExportExcelController<MemberUserBehaviorBean> export = new ExportExcelController<>();
        export.exportExcel(fileName, fileName, columnNames, columns,
                memberUserBehaviorParamBeans, response, ExportExcelUtil.EXCEL_FILE_2003);
    }


    /**
     * 复投用户统计总表
     * @param accessToken
     * @param memberUserBuyGoldParamBean
     * @return
     */
    @RequestMapping(value = "againBuy/list", method = GET)
    public SerializeObject<DataTable<MemberUserAgainBuyBean>> againBuylist(@RequestHeader String accessToken, Page page, MemberUserAgainBuyParamBean memberUserAgainBuyParamBean) {
        if (page.getPageSize() <= 0) {
            page.setPageSize(config.getPageSize());
        }

        //解决一个奇怪的问题 前端传值会在前面加一个逗号。。
        if (StringUtils.isNotBlank(memberUserAgainBuyParamBean.getOrder()) && memberUserAgainBuyParamBean.getOrder().contains(",")){
            memberUserAgainBuyParamBean.setOrder(memberUserAgainBuyParamBean.getOrder().replaceAll(",",""));
            memberUserAgainBuyParamBean.setSort(memberUserAgainBuyParamBean.getSort().replaceAll(",",""));
        }
        List<MemberUserAgainBuyBean> beans = memberUserService.queryAgainBuyUserList(memberUserAgainBuyParamBean);
        //DataTable<MemberUserAgainBuyBean> dataTable = memberUserService.queryAgainBuyUserList(memberUserAgainBuyParamBean);

        //累计复投金额区间
        if (memberUserAgainBuyParamBean.getStartRepeatAmount() != null && memberUserAgainBuyParamBean.getEndRepeatAmount() != null
                && memberUserAgainBuyParamBean.getEndRepeatAmount().compareTo(memberUserAgainBuyParamBean.getStartRepeatAmount()) < 0) {
            return new SerializeObjectError("14000262");
        }

        if (CollectionUtils.isEmpty(beans)) {
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberUserAgainBuyBean>(page.getPageNum(), page.getPageSize(), 0, new ArrayList<MemberUserAgainBuyBean>()));
        }

        List<MemberUserAgainBuyBean> amountBeans = new ArrayList<>();
        if (memberUserAgainBuyParamBean.getStartRepeatAmount() != null || memberUserAgainBuyParamBean.getEndRepeatAmount() != null) {
            BigDecimal startAmount = memberUserAgainBuyParamBean.getStartRepeatAmount() == null ? BigDecimal.ZERO : memberUserAgainBuyParamBean.getStartRepeatAmount();
            BigDecimal endAmount = memberUserAgainBuyParamBean.getEndRepeatAmount() == null ? new BigDecimal(Long.MAX_VALUE) : memberUserAgainBuyParamBean.getEndRepeatAmount();

            for (MemberUserAgainBuyBean dataBean  : beans) {
                dataBean.setTotalRepeatAmount(dataBean.getTotalRepeatAmount() == null ? BigDecimal.ZERO : dataBean.getTotalRepeatAmount());

                if (dataBean.getTotalRepeatAmount().compareTo(startAmount) > -1 && dataBean.getTotalRepeatAmount().compareTo(endAmount) < 1) {
                    amountBeans.add(dataBean);
                }
            }
            beans.clear();
            beans.addAll(amountBeans);
        }
        if (CollectionUtils.isEmpty(beans)) {
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberUserAgainBuyBean>(page.getPageNum(), page.getPageSize(), 0, new ArrayList<MemberUserAgainBuyBean>()));
        }


        //累计复投克重区间
        if (memberUserAgainBuyParamBean.getStartRepeatGram() != null && memberUserAgainBuyParamBean.getEndRepeatGram() != null
                && memberUserAgainBuyParamBean.getEndRepeatGram() < memberUserAgainBuyParamBean.getStartRepeatGram()) {
            return new SerializeObjectError("14000262");
        }

        List<MemberUserAgainBuyBean> gramBeans = new ArrayList<>();
        if (memberUserAgainBuyParamBean.getStartRepeatGram() != null || memberUserAgainBuyParamBean.getEndRepeatGram() != null) {
            Integer startGram = memberUserAgainBuyParamBean.getStartRepeatGram() == null ? 0 : memberUserAgainBuyParamBean.getStartRepeatGram();
            Integer endGram = memberUserAgainBuyParamBean.getEndRepeatGram() == null ? Integer.MAX_VALUE : memberUserAgainBuyParamBean.getEndRepeatGram();

            for (MemberUserAgainBuyBean dataBean  : beans) {
                dataBean.setTotalRepeatGram(dataBean.getTotalRepeatGram() == null ? 0 : dataBean.getTotalRepeatGram());

                if (dataBean.getTotalRepeatGram() >= startGram && dataBean.getTotalRepeatGram() <= endGram) {
                    gramBeans.add(dataBean);
                }
            }
            beans.clear();
            beans.addAll(amountBeans);
        }
        if (CollectionUtils.isEmpty(beans)) {
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberUserAgainBuyBean>(page.getPageNum(), page.getPageSize(), 0, new ArrayList<MemberUserAgainBuyBean>()));
        }

        //累计复投次数区间过滤

        if (memberUserAgainBuyParamBean.getStartRepeatNum() != null && memberUserAgainBuyParamBean.getEndRepeatNum() != null
                && memberUserAgainBuyParamBean.getEndRepeatNum() < memberUserAgainBuyParamBean.getStartRepeatNum()) {
            return new SerializeObjectError("14000262");
        }

        List<MemberUserAgainBuyBean> numBeans = new ArrayList<>();
        if (memberUserAgainBuyParamBean.getStartRepeatNum() != null || memberUserAgainBuyParamBean.getEndRepeatNum() != null) {
            Integer startNum = memberUserAgainBuyParamBean.getStartRepeatNum() == null ? 0 : memberUserAgainBuyParamBean.getStartRepeatNum();
            Integer endNum = memberUserAgainBuyParamBean.getEndRepeatNum() == null ? Integer.MAX_VALUE : memberUserAgainBuyParamBean.getEndRepeatNum();

            for (MemberUserAgainBuyBean dataBean  : beans) {
                dataBean.setTotalRepeatNum(dataBean.getTotalRepeatNum() == null ? 0 : dataBean.getTotalRepeatNum());

                if (dataBean.getTotalRepeatNum() >= startNum && dataBean.getTotalRepeatNum() <= endNum) {
                    numBeans.add(dataBean);
                }
            }
            beans.clear();
            beans.addAll(numBeans);
        }
        if (CollectionUtils.isEmpty(beans)) {
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberUserAgainBuyBean>(page.getPageNum(), page.getPageSize(), 0, new ArrayList<MemberUserAgainBuyBean>()));
        }


        //排序，默认按照累计复投次数倒序排列
        if (StringUtils.isBlank(memberUserAgainBuyParamBean.getOrder())) {
            memberUserAgainBuyParamBean.setOrder("totalRepeatNum");
            memberUserAgainBuyParamBean.setSort("desc");
        }
        if (memberUserAgainBuyParamBean.getOrder().equalsIgnoreCase("totalRepeatNum")) {
            if (memberUserAgainBuyParamBean.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getTotalRepeatNum));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getTotalRepeatNum).reversed());
            }
        }

        if (memberUserAgainBuyParamBean.getOrder().equalsIgnoreCase("totalRepeatGram")) {
            if (memberUserAgainBuyParamBean.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getTotalRepeatGram));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getTotalRepeatGram).reversed());
            }
        }

        if (memberUserAgainBuyParamBean.getOrder().equalsIgnoreCase("totalRepeatAmount")) {
            if (memberUserAgainBuyParamBean.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getTotalRepeatAmount));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getTotalRepeatAmount).reversed());
            }
        }

        if (memberUserAgainBuyParamBean.getOrder().equalsIgnoreCase("maxRepeatGram")) {
            if (memberUserAgainBuyParamBean.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getMaxRepeatGram));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getMaxRepeatGram).reversed());
            }
        }

        if (memberUserAgainBuyParamBean.getOrder().equalsIgnoreCase("maxRepeatAmount")) {
            if (memberUserAgainBuyParamBean.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getMaxRepeatAmount));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getMaxRepeatAmount).reversed());
            }
        }

        page.setPageSize(page.getPageSize());
        page.setPageNum(page.getPageNum());
        page.setTotal(beans.size());

        //合计值
        Map map = memberUserService.countAgainBuyUser(memberUserAgainBuyParamBean);
        Integer totalRepeatNumCount = 0;
        BigDecimal totalRepeatAmountCount = BigDecimal.ZERO;
        Integer totalRepeatGramCount = 0;
        if (!CollectionUtils.isEmpty(beans)) {
            int index = 1;
            for (MemberUserAgainBuyBean bean : beans) {
                if (null != bean.getTotalRepeatNum()) {
                    totalRepeatNumCount = totalRepeatNumCount + bean.getTotalRepeatNum();
                }
                if (null != bean.getTotalRepeatAmount()) {
                    totalRepeatAmountCount = totalRepeatAmountCount.add(bean.getTotalRepeatAmount());
                }
                if (null != bean.getTotalRepeatGram()) {
                    totalRepeatGramCount = totalRepeatGramCount + bean.getTotalRepeatGram();
                }
                bean.setIndex(index++);
            }
        }
        map.put("totalRepeatNumCount",totalRepeatNumCount);
        map.put("totalRepeatAmountCount",totalRepeatAmountCount);
        map.put("totalRepeatGramCount",totalRepeatGramCount);

        if (page.getPageSize() > 0) {
            beans = beans.stream().skip((PaginationUtil.getPage(page.getPageNum()) - 1) * page.getPageSize()).limit(page.getPageSize()).collect(Collectors.toList());
        }

        return new SerializeObject<>(ResultType.NORMAL, new DataOtherTable<MemberUserAgainBuyBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), beans,map));
    }


    /**
     * 复投用户统计导出
     *
     * @param response
     * @param memberUserAgainBuyParamBean
     */
    @RequestMapping(value = "/againBuy/export", method = GET)
    public void againBuyExport(HttpServletResponse response, MemberUserAgainBuyParamBean memberUserAgainBuyParamBean) {

        String[] columnNames = {"序号", "手机号", "用户姓名", "渠道来源", "累计复投次数（次）", "累计复投克重（克）", "累计复投总金额（元）", "单笔复投最高克重（克）", "单笔复投最高金额（元）"};
        String[] columns = {"index", "mobile", "name", "channelName", "totalRepeatNum", "totalRepeatGram", "totalRepeatAmount", "maxRepeatGram", "maxRepeatAmount"};
        String fileName = "复投用户统计总表";
        //memberUserAgainBuyParamBean.setPageSize(Integer.MAX_VALUE);

        if (StringUtils.isNotBlank(memberUserAgainBuyParamBean.getOrder()) && memberUserAgainBuyParamBean.getOrder().contains(",")){
            memberUserAgainBuyParamBean.setOrder(memberUserAgainBuyParamBean.getOrder().replaceAll(",",""));
            memberUserAgainBuyParamBean.setSort(memberUserAgainBuyParamBean.getSort().replaceAll(",",""));
        }
        List<MemberUserAgainBuyBean> beans = memberUserService.queryAgainBuyUserList(memberUserAgainBuyParamBean);

        //累计复投金额区间
        if (memberUserAgainBuyParamBean.getStartRepeatAmount() != null && memberUserAgainBuyParamBean.getEndRepeatAmount() != null
                && memberUserAgainBuyParamBean.getEndRepeatAmount().compareTo(memberUserAgainBuyParamBean.getStartRepeatAmount()) < 0) {
            //抛出异常
            return;
        }

        if (!CollectionUtils.isEmpty(beans)) {
            List<MemberUserAgainBuyBean> amountBeans = new ArrayList<>();
            if (memberUserAgainBuyParamBean.getStartRepeatAmount() != null || memberUserAgainBuyParamBean.getEndRepeatAmount() != null) {
                BigDecimal startAmount = memberUserAgainBuyParamBean.getStartRepeatAmount() == null ? BigDecimal.ZERO : memberUserAgainBuyParamBean.getStartRepeatAmount();
                BigDecimal endAmount = memberUserAgainBuyParamBean.getEndRepeatAmount() == null ? new BigDecimal(Long.MAX_VALUE) : memberUserAgainBuyParamBean.getEndRepeatAmount();

                for (MemberUserAgainBuyBean dataBean : beans) {
                    dataBean.setTotalRepeatAmount(dataBean.getTotalRepeatAmount() == null ? BigDecimal.ZERO : dataBean.getTotalRepeatAmount());

                    if (dataBean.getTotalRepeatAmount().compareTo(startAmount) > -1 && dataBean.getTotalRepeatAmount().compareTo(endAmount) < 1) {
                        amountBeans.add(dataBean);
                    }
                }
                beans.clear();
                beans.addAll(amountBeans);
            }
        }

        //累计复投克重区间
        if (memberUserAgainBuyParamBean.getStartRepeatGram() != null && memberUserAgainBuyParamBean.getEndRepeatGram() != null
                && memberUserAgainBuyParamBean.getEndRepeatGram() < memberUserAgainBuyParamBean.getStartRepeatGram()) {
            return ;
        }

        if (!CollectionUtils.isEmpty(beans)) {
            List<MemberUserAgainBuyBean> gramBeans = new ArrayList<>();
            if (memberUserAgainBuyParamBean.getStartRepeatGram() != null || memberUserAgainBuyParamBean.getEndRepeatGram() != null) {
                Integer startGram = memberUserAgainBuyParamBean.getStartRepeatGram() == null ? 0 : memberUserAgainBuyParamBean.getStartRepeatGram();
                Integer endGram = memberUserAgainBuyParamBean.getEndRepeatGram() == null ? Integer.MAX_VALUE : memberUserAgainBuyParamBean.getEndRepeatGram();

                for (MemberUserAgainBuyBean dataBean  : beans) {
                    dataBean.setTotalRepeatGram(dataBean.getTotalRepeatGram() == null ? 0 : dataBean.getTotalRepeatGram());

                    if (dataBean.getTotalRepeatGram() >= startGram && dataBean.getTotalRepeatGram() <= endGram) {
                        gramBeans.add(dataBean);
                    }
                }
                beans.clear();
                beans.addAll(gramBeans);
            }
        }

        //累计复投次数区间过滤
        if (memberUserAgainBuyParamBean.getStartRepeatNum() != null && memberUserAgainBuyParamBean.getEndRepeatNum() != null
                && memberUserAgainBuyParamBean.getEndRepeatNum() < memberUserAgainBuyParamBean.getStartRepeatNum()) {
            return;
        }

        if (!CollectionUtils.isEmpty(beans)) {
            List<MemberUserAgainBuyBean> numBeans = new ArrayList<>();
            if (memberUserAgainBuyParamBean.getStartRepeatNum() != null || memberUserAgainBuyParamBean.getEndRepeatNum() != null) {
                Integer startNum = memberUserAgainBuyParamBean.getStartRepeatNum() == null ? 0 : memberUserAgainBuyParamBean.getStartRepeatNum();
                Integer endNum = memberUserAgainBuyParamBean.getEndRepeatNum() == null ? Integer.MAX_VALUE : memberUserAgainBuyParamBean.getEndRepeatNum();

                for (MemberUserAgainBuyBean dataBean  : beans) {
                    dataBean.setTotalRepeatNum(dataBean.getTotalRepeatNum() == null ? 0 : dataBean.getTotalRepeatNum());

                    if (dataBean.getTotalRepeatNum() >= startNum && dataBean.getTotalRepeatNum() <= endNum) {
                        numBeans.add(dataBean);
                    }
                }
                beans.clear();
                beans.addAll(numBeans);
            }
        }

        //排序，默认按照累计复投次数倒序排列
        if (StringUtils.isBlank(memberUserAgainBuyParamBean.getOrder())) {
            memberUserAgainBuyParamBean.setOrder("totalRepeatNum");
            memberUserAgainBuyParamBean.setSort("desc");
        }

        if (!CollectionUtils.isEmpty(beans)) {
            if (memberUserAgainBuyParamBean.getOrder().equalsIgnoreCase("totalRepeatNum")) {
                if (memberUserAgainBuyParamBean.getSort().equalsIgnoreCase("asc")) {
                    Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getTotalRepeatNum));
                } else {
                    Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getTotalRepeatNum).reversed());
                }
            }

            if (memberUserAgainBuyParamBean.getOrder().equalsIgnoreCase("totalRepeatGram")) {
                if (memberUserAgainBuyParamBean.getSort().equalsIgnoreCase("asc")) {
                    Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getTotalRepeatGram));
                } else {
                    Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getTotalRepeatGram).reversed());
                }
            }

            if (memberUserAgainBuyParamBean.getOrder().equalsIgnoreCase("totalRepeatAmount")) {
                if (memberUserAgainBuyParamBean.getSort().equalsIgnoreCase("asc")) {
                    Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getTotalRepeatAmount));
                } else {
                    Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getTotalRepeatAmount).reversed());
                }
            }

            if (memberUserAgainBuyParamBean.getOrder().equalsIgnoreCase("maxRepeatGram")) {
                if (memberUserAgainBuyParamBean.getSort().equalsIgnoreCase("asc")) {
                    Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getMaxRepeatGram));
                } else {
                    Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getMaxRepeatGram).reversed());
                }
            }

            if (memberUserAgainBuyParamBean.getOrder().equalsIgnoreCase("maxRepeatAmount")) {
                if (memberUserAgainBuyParamBean.getSort().equalsIgnoreCase("asc")) {
                    Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getMaxRepeatAmount));
                } else {
                    Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyBean::getMaxRepeatAmount).reversed());
                }
            }
        }


        //合计值
        Map map = memberUserService.countAgainBuyUser(memberUserAgainBuyParamBean);
        Integer totalRepeatNumCount = 0;
        BigDecimal totalRepeatAmountCount = BigDecimal.ZERO;
        Integer totalRepeatGramCount = 0;
        if (!CollectionUtils.isEmpty(beans)) {
            int index = 1;
            for (MemberUserAgainBuyBean bean : beans) {
                if (null != bean.getTotalRepeatNum()) {
                    totalRepeatNumCount = totalRepeatNumCount + bean.getTotalRepeatNum();
                }
                if (null != bean.getTotalRepeatAmount()) {
                    totalRepeatAmountCount = totalRepeatAmountCount.add(bean.getTotalRepeatAmount());
                }
                if (null != bean.getTotalRepeatGram()) {
                    totalRepeatGramCount = totalRepeatGramCount + bean.getTotalRepeatGram();
                }
                bean.setIndex(index++);
            }
        }

        String[] firstLines = {"合计", map.get("memberIdCount") == null ? "0" : map.get("memberIdCount") + "人", map.get("memberIdCount") == null ? "0" : map.get("memberIdCount") + "人",
                "/", totalRepeatNumCount + "次", totalRepeatGramCount + "克", totalRepeatAmountCount + "元","/","/"};

        ExportExcelController<MemberUserAgainBuyBean> export = new ExportExcelController<>();
        export.exportUnlikeExcel(fileName, fileName, columnNames, columns,
                beans, response, ExportExcelUtil.EXCEL_FILE_2003,firstLines);


    }


    /**
     * 复投用户统计详情表
     * @param accessToken
     * @param memberUserBuyGoldParamBean
     * @return
     */
    @RequestMapping(value = "againBuy/detail", method = GET)
    public SerializeObject<DataTable<MemberUserAgainBuyBean>> againBuyLeasebacklist(@RequestHeader String accessToken, Page page, Order order, String memberId,Integer[] leasebackDays,Integer[] productType) {
        if (StringUtils.isBlank(memberId)) {
            return new SerializeObjectError("14000227");
        }

        if (page.getPageSize() <= 0) {
            page.setPageSize(config.getPageSize());
        }

        //解决一个奇怪的问题 前端传值会在前面加一个逗号。。
        if (StringUtils.isNotBlank(order.getOrder()) && order.getOrder().contains(",")){
            order.setOrder(order.getOrder().replaceAll(",",""));
            order.setSort(order.getSort().replaceAll(",",""));
        }

        List<MemberUserAgainBuyLeasebackBean> beans = memberUserService.queryAgainBuyUserLeaseback(memberId,leasebackDays,productType);
        //DataTable<MemberUserAgainBuyBean> dataTable = memberUserService.queryAgainBuyUserList(memberUserAgainBuyParamBean);

        //排序，默认按照复投到期时间排列
        if (StringUtils.isBlank(order.getOrder())) {
            order.setOrder("endTime");
            order.setSort("desc");
        }
        if (order.getOrder().equalsIgnoreCase("repeatGram")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getRepeatGram));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getRepeatGram).reversed());
            }
        }

        if (order.getOrder().equalsIgnoreCase("repeatAmount")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getRepeatAmount));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getRepeatAmount).reversed());
            }
        }

        if (order.getOrder().equalsIgnoreCase("goldPrice")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getGoldPrice));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getGoldPrice).reversed());
            }
        }

        if (order.getOrder().equalsIgnoreCase("startTime")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getStartTime));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getStartTime).reversed());
            }
        }

        if (order.getOrder().equalsIgnoreCase("endTime")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getEndTime));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getEndTime).reversed());
            }
        }

        page.setPageSize(page.getPageSize());
        page.setPageNum(page.getPageNum());
        page.setTotal(beans.size());

        //合计值
        Map map = new HashMap();
        Integer tbillNoCount = 0;
        Integer orderNoCount = 0;
        Integer repeatGramCount = 0;
        BigDecimal repeatAmountCount = BigDecimal.ZERO;
        Set tbillSet = new HashSet();
        Set orderNoSet = new HashSet();
        if (!CollectionUtils.isEmpty(beans)) {
            int index = 1;
            for (MemberUserAgainBuyLeasebackBean bean : beans) {
                if (StringUtils.isNotBlank(bean.getTbillNo())) {
                    tbillSet.add(bean.getTbillNo());
                }
                if (StringUtils.isNotBlank(bean.getOrderNo())) {
                    orderNoSet.add(bean.getOrderNo());
                }
                if (null != bean.getRepeatGram()) {
                    repeatGramCount = repeatGramCount + bean.getRepeatGram();
                }
                if (null != bean.getRepeatAmount()) {
                    repeatAmountCount = repeatAmountCount.add(bean.getRepeatAmount());
                }
                bean.setIndex(index++);
            }
        }
        map.put("tbillNoCount",tbillSet.size());
        map.put("orderNoCount",orderNoSet.size());
        map.put("repeatGramCount",repeatGramCount);
        map.put("repeatAmountCount",repeatAmountCount);

        if (page.getPageSize() > 0) {
            beans = beans.stream().skip((PaginationUtil.getPage(page.getPageNum()) - 1) * page.getPageSize()).limit(page.getPageSize()).collect(Collectors.toList());
        }

        return new SerializeObject<>(ResultType.NORMAL, new DataOtherTable<MemberUserAgainBuyLeasebackBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), beans,map));
    }

    /**
     * 复投用户统计详情表导出
     * @param accessToken
     * @param page
     * @param order
     * @param memberId
     * @param leasebackDays
     * @param productIds
     */
    @RequestMapping(value="againBuy/detail/export",method = GET)
    public void againBuyUserDetail(HttpServletResponse response,String memberId,Integer[] leasebackDays,Integer[] productType,Order order){
        if (StringUtils.isBlank(memberId)) {
            return;
        }

        if (StringUtils.isNotBlank(order.getOrder()) && order.getOrder().contains(",")){
            order.setOrder(order.getOrder().replaceAll(",",""));
            order.setSort(order.getSort().replaceAll(",",""));
        }

        String[] columnNames = {"序号", "复投提单编号", "操作流水号", "复投产品类型", "复投克重（克）", "复投提单金额（元）", "复投时金价（元/克）", "复投提单期限（天）", "复投开始时间","复投到期时间"};
        String[] columns = {"index", "tbillNo", "orderNo", "productName", "repeatGram", "repeatAmount", "goldPrice", "leasebackDays", "startTime","endTime"};
        String fileName = "复投用户统计详表";

        List<MemberUserAgainBuyLeasebackBean> beans = memberUserService.queryAgainBuyUserLeaseback(memberId,leasebackDays,productType);

        //排序，默认按照复投到期时间排列
        if (StringUtils.isBlank(order.getOrder())) {
            order.setOrder("endTime");
            order.setSort("desc");
        }


        if (order.getOrder().equalsIgnoreCase("repeatGram")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getRepeatGram));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getRepeatGram).reversed());
            }
        }

        if (order.getOrder().equalsIgnoreCase("repeatAmount")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getRepeatAmount));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getRepeatAmount).reversed());
            }
        }

        if (order.getOrder().equalsIgnoreCase("goldPrice")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getGoldPrice));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getGoldPrice).reversed());
            }
        }

        if (order.getOrder().equalsIgnoreCase("startTime")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getStartTime));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getStartTime).reversed());
            }
        }

        if (order.getOrder().equalsIgnoreCase("endTime")) {
            if (order.getSort().equalsIgnoreCase("asc")) {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getEndTime));
            } else {
                Collections.sort(beans, Comparator.comparing(MemberUserAgainBuyLeasebackBean::getEndTime).reversed());
            }
        }

        //合计值
        Map map = new HashMap();
        Integer tbillNoCount = 0;
        Integer orderNoCount = 0;
        Integer repeatGramCount = 0;
        BigDecimal repeatAmountCount = BigDecimal.ZERO;
        Set tbillSet = new HashSet();
        Set orderNoSet = new HashSet();
        if (!CollectionUtils.isEmpty(beans)) {
            int index = 1;
            for (MemberUserAgainBuyLeasebackBean bean : beans) {
                if (StringUtils.isNotBlank(bean.getTbillNo())) {
                    tbillSet.add(bean.getTbillNo());
                }
                if (StringUtils.isNotBlank(bean.getOrderNo())) {
                    orderNoSet.add(bean.getOrderNo());
                }
                if (null != bean.getRepeatGram()) {
                    repeatGramCount = repeatGramCount + bean.getRepeatGram();
                }
                if (null != bean.getRepeatAmount()) {
                    repeatAmountCount = repeatAmountCount.add(bean.getRepeatAmount());
                }
                bean.setIndex(index);
                index++;
            }
        }
        map.put("tbillNoCount",tbillSet.size());
        map.put("orderNoCount",orderNoSet.size());
        map.put("repeatGramCount",repeatGramCount);
        map.put("repeatAmountCount",repeatAmountCount);

        String[] firstLines = {"合计", tbillNoCount + "笔", orderNoCount + "次",
                "全部", repeatGramCount + "克", repeatAmountCount + "元"
                ,"/","/", "/", "/"};
        ExportExcelController<MemberUserAgainBuyLeasebackBean> export = new ExportExcelController<MemberUserAgainBuyLeasebackBean>();
        export.exportUnlikeExcel(fileName, fileName, columnNames, columns, beans, response, ExportExcelUtil.EXCEL_FILE_2003, firstLines);
    }

    /**
     * 获取用户最早添加时间
     * @return
     */
    @RequestMapping(value = "/findMinAddTime", method = GET)
    public SerializeObject<Date> findMinAddTime() {
        return new SerializeObject<>(ResultType.NORMAL, memberUserService.findMinAddTime());
    }

    private List<MemberUserExportBaseBean> wrapPutGoldBeanData(List<MemberUserBaseBean> list) {
        int index = 1;
        List<MemberUserExportBaseBean> memberUserExportBaseBeanList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            for (MemberUserBaseBean bean : list) {
                MemberUserExportBaseBean memberUserExportBaseBean = new MemberUserExportBaseBean();
                BeanUtils.copyProperties(bean, memberUserExportBaseBean);
                memberUserExportBaseBean.setIndex(index++);
                memberUserExportBaseBean.setUserStatus(bean.getStatus() == 1 ? "正常" : "冻结");
                memberUserExportBaseBeanList.add(memberUserExportBaseBean);
            }
        }
        return memberUserExportBaseBeanList;
    }

    private String invoke(String url) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        try {

            CloseableHttpResponse httpResponse = closeableHttpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            httpGet.releaseConnection();
        }
        return null;
    }

    public String getMD5(String need2Encode) throws NoSuchAlgorithmException {
        byte[] buf = need2Encode.getBytes();
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(buf);
        byte[] tmp = md5.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : tmp) {
            if (b >= 0 && b < 16)
                sb.append("0");
            sb.append(Integer.toHexString(b & 0xff));
        }
        return sb.toString();
    }
}
